/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.toools.gwt.wmc.server.dao.toplink;

import java.util.Collection;
import javax.persistence.NoResultException;
import oracle.toplink.essentials.ejb.cmp3.EntityManager;
import oracle.toplink.essentials.expressions.Expression;
import oracle.toplink.essentials.expressions.ExpressionBuilder;
import org.springframework.stereotype.Repository;
import org.toools.gwt.wmc.jpa.Additive;
import org.toools.gwt.wmc.jpa.Application;
import org.toools.gwt.wmc.jpa.Company;
import org.toools.gwt.wmc.server.dao.ICompanyPartDAO;
import org.toools.gwt.wmc.jpa.CompanyPart;

/**
 *
 * @author ich
 */
@Repository
public class CompanyPartDAO implements ICompanyPartDAO{

//    private EntityManager em;
//
//    @PersistenceContext
//    public void setEntityManager( EntityManager em ) {
//        this.em = em;
//    }

    public CompanyPart getCompanyPartByID(Integer id) {
        CompanyPart result;
        try {
            result = (CompanyPart) EMFKeeper.EM.createNamedQuery("CompanyPart.getById").setParameter("id", id).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        System.out.println("fetched companypart " + result.getId() + " from db.");
        return result;
    }

    public Boolean belongsTo( Integer id, Integer accountid ) {
        
        EntityManager em = (EntityManager)EMFKeeper.EM;
        ExpressionBuilder eb = new ExpressionBuilder();
        //company mit zugehörigemm account
        Expression companypart = eb.get( "id" ).equal( id );
        Expression acc = eb.get( "company" ).get("account").get("id").equal( accountid );
        Expression belongsto = companypart.and( acc );

        return em.getSession().readAllObjects( CompanyPart.class, belongsto ).size() > 0;
    }

    public Collection<CompanyPart> getCompanyParts() {
        Collection<CompanyPart> ret = EMFKeeper.EM.createNamedQuery("CompanyPart.getAll").getResultList();

        System.out.println("fetched " + ret.size() + " companyparts from db.");
        return ret;
    }
    
    public Collection<CompanyPart> getCompanyParts(Integer accountid) {
        EntityManager em = (EntityManager)EMFKeeper.EM;

        ExpressionBuilder eb = new ExpressionBuilder();
        Expression res = eb.get("company").get( "account" ).get( "id" ).equal( accountid );

        Collection<CompanyPart> ret = em.getSession().readAllObjects( Company.class, res );
        return ret;
    }

    public CompanyPart create(CompanyPart c) {
        return SimpleCUD.create( c );
    }

    public Boolean delete(CompanyPart c) {
        CompanyPart rem = (CompanyPart) EMFKeeper.EM.createNamedQuery( "CompanyPart.getById" ).setParameter( "id", c.getId() ).getSingleResult();
        return SimpleCUD.delete( rem );
    }

    public Boolean update(CompanyPart c) {
        return SimpleCUD.update( c );
    }
}
